package com.java80.littlegame.service.gateway.websocket.net;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.java80.littlegame.common.msg.BaseMsg;
import com.java80.littlegame.common.msg.ProtoHelper;
import com.java80.littlegame.service.gateway.session.ChannelManageCenter;
import com.java80.littlegame.service.gateway.session.ConnectSession;
import com.java80.littlegame.service.gateway.websocket.MessageHelper;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @author www.java80.com
 * @date 2018年3月11日 下午4:37:45
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	private static Logger log = LoggerFactory.getLogger(WebSocketHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		log.debug("服务器收到：{}", msg.text());
		String text = msg.text();
		// ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器收到您的消息：" +
		// text + ""));
		BaseMsg baseMsg = ProtoHelper.parseJSON(text);
		ConnectSession session = ChannelManageCenter.getInstance().getSession(ctx.channel());
		if (session != null) {
			baseMsg.setSessionId(session.getSesseionId());
			baseMsg.setSenderUserId(session.getUserId());
			baseMsg.setRecUserId(session.getUserId());
		} else {
			baseMsg.setSessionId(ChannelManageCenter.getInstance().getTempID(ctx.channel()));
		}
		MessageHelper.dispatchMsg(baseMsg);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		ChannelManageCenter.getInstance().addChannel(ctx.channel());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("exceptionCaught");
		super.exceptionCaught(ctx, cause);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		try {
			ChannelManageCenter.getInstance().removeTempSession(ctx.channel());
			ConnectSession session = ChannelManageCenter.getInstance().getSession(ctx.channel());
			if (session != null) {
				// GameMessageDispatcher.removeGameCluster(session.getUserId());
				// ChannelManageCenter.getInstance().removeSessionPool(session.getUserId());
				// ClusterEvent event = new
				// ClusterEvent(NetEventConst.DisconnectEvent);
				// event.addParams("userId", session.getUserId());
				// dispather.dispatchEvent(ClusterMessageConst.USER_CLUSTER_EVENT,
				// event);
			}
			Channel channel = ctx.channel();
			channel.close();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		super.handlerRemoved(ctx);
	}

}
